package service

import (
	"context"

	"gitee.com/gldmmhh/bbs/data_service"
	"gitee.com/gldmmhh/bbs/utils"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/user"
)

// GetUserInfo 获取用户信息业务逻辑
func GetUserInfo(userID int64) (*user.GetUserResponse, error) {
	// 调用数据服务层获取用户信息
	userInfo, err := data_service.GetUserInfo(userID)
	if err != nil {
		return &user.GetUserResponse{
			Code:    500,
			Message: "获取用户信息失败",
		}, nil
	}

	if userInfo == nil {
		return &user.GetUserResponse{
			Code:    404,
			Message: "用户不存在",
		}, nil
	}

	return &user.GetUserResponse{
		Code:    200,
		Message: "success",
		Data:    utils.DaUserToUser(userInfo),
	}, nil
}

// FollowUserLogic 关注用户业务逻辑
func FollowUserLogic(userID, followerID int64) (*user.FollowUserResponse, error) {
	err := data_service.FollowUser(userID, followerID)
	if err != nil {
		return &user.FollowUserResponse{
			Code:    500,
			Message: "关注失败: " + err.Error(),
		}, nil
	}

	return &user.FollowUserResponse{
		Code:    200,
		Message: "关注成功",
	}, nil
}

func LoginLogic(ctx context.Context, req *user.LoginRequest) (*user.LoginResponse, error) {
	// 校验数据
	userName := req.Username
	password := req.Password
	// 调用数据服务层验证用户信息
	dbUser, err := data_service.GetUserByUserName(userName)
	if err != nil {
		return &user.LoginResponse{
			Code:    500,
			Message: "登录失败: " + err.Error(),
		}, nil
	}
	if dbUser.PassWord != password {
		return &user.LoginResponse{
			Code:    401,
			Message: "密码错误",
		}, nil
	}
	return &user.LoginResponse{
		Code:    200,
		Message: "登录成功",
		User:    utils.DaUserToUser(dbUser),
	}, nil
}

func RegisterLogic(username, password string) (*user.RegisterResponse, error) {
	// 调用数据服务层验证用户信息
	userInfo, err := data_service.Register(username, password)
	if err != nil {
		return &user.RegisterResponse{
			Code:    500,
			Message: "注册失败: " + err.Error(),
		}, nil
	}
	return &user.RegisterResponse{
		Code:    200,
		Message: "注册成功",
		UserId:  userInfo.Id,
	}, nil
}

// GetFollowingLogic 获取关注列表业务逻辑
func GetFollowingLogic(userID int64, page, size int) (*user.GetFollowingResponse, error) {
	followingList, total, err := data_service.GetFollowingList(userID, page, size)
	if err != nil {
		return &user.GetFollowingResponse{
			Code:    500,
			Message: "获取关注列表失败",
		}, nil
	}

	followingUsers := make([]*user.FollowingUser, 0, len(followingList))
	for _, u := range followingList {
		followingUsers = append(followingUsers, &user.FollowingUser{
			Id:          u.Id,
			Name:        u.Name,
			Type:        u.Type,
			FollowNum:   u.FollowNum,
			FollowerNum: u.FollowerNum,
			PostNum:     u.PostNum,
		})
	}

	pages := (total + int64(size) - 1) / int64(size)
	return &user.GetFollowingResponse{
		Code:    200,
		Message: "success",
		Data: &user.FollowingData{
			Total:       total,
			Pages:       pages,
			CurrentPage: int64(page),
			Following:   followingUsers,
		},
	}, nil
}
